import { GetUserOpenId, UserLoginByRole } from '@/api/user';
import SwitchIdentities from '@/components/SwitchIdentities';
import useCustomerService from '@/components/useCustomerService';
import useRole from '@/hooks/useRole';
import { Button } from '@antmjs/vantui';
import {
  BaseEventOrig,
  ButtonProps,
  Image,
  Text,
  View,
} from '@tarojs/components';
import Taro, { useLoad } from '@tarojs/taro';
import { useRequest } from 'taro-hooks';
import { RoleType } from 'types/user';
import { useAgree } from './components/useAgree';
import { ROLE_HOMEPAGE_MAP, ShowErrorInfoByCode } from './util';

export default function Page() {
  const { role, update: updateRole } = useRole();
  const { runAsync, loading } = useRequest(UserLoginByRole, {
    manual: true,
  });

  const { agree, renderNode: renderAgreeNode } = useAgree();
  const { renderNode: renderServiceNode, open: openService } =
    useCustomerService();

  async function handleGetPhoneNumber(
    e: BaseEventOrig<ButtonProps.onGetPhoneNumberEventDetail>
  ) {
    if (!agree) {
      e.stopPropagation();
      return Taro.showToast({ title: '请先阅读并同意协议', icon: 'none' });
    }

    const { code, errMsg } = e.detail;

    if (errMsg !== 'getPhoneNumber:ok')
      return Taro.showToast({
        title: '授权失败',
        icon: 'error',
      });
    if (!code) return;
    try {
      const res = await runAsync({
        code,
        role,
        reg_code: Taro.getStorageSync('refer_code') || '',
      });

      //缓存token
      res?.token && Taro.setStorageSync('token', res.token);

      //判断用户状态
      if (!res) await Taro.showToast({ title: '用户异常', icon: 'none' });

      //审核中处理
      if (res.status === 0) {
        return Taro.redirectTo({
          url: res.name ? '/pages/info/success' : `/pages/info/index`,
        });
      }

      //更新角色
      res.role && updateRole(res.role);

      //登录成功后， 根据角色跳转
      Taro.reLaunch({
        url: ROLE_HOMEPAGE_MAP[res?.role] || ROLE_HOMEPAGE_MAP[RoleType.用户],
      });
    } catch (error: any) {
      const code = error?.code;
      code &&
        ShowErrorInfoByCode(code, function () {
          //这里打开客服
          openService();
        });
    }
  }

  useLoad(() => {
    GetUserOpenId();
  });

  return (
    <View
      className=' min-h-screen bg-cover pt-[300px]'
      style={{
        backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/bg1.jpg)`,
      }}
    >
      <View className=' absolute right-2 top-[200px]'>
        <SwitchIdentities />
      </View>

      <Image
        src='https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/logo.png'
        mode='aspectFill'
        className='w-[240px] h-[254px] block mx-auto'
      />

      <View className='flex justify-center items-center mt-[58px]'>
        <Text className=' text-center text-xs opacity-45 text-white'>
          臻会帮企业服务平台 -{role === RoleType.用户 && <>用户端</>}
          {role === RoleType.专家 && <>专家端</>}
          {role === RoleType.合伙人 && <>合伙人端</>}
        </Text>
      </View>

      <View className=' absolute bottom-[60px] left-0 right-0 flex flex-col items-center'>
        <Button
          loading={loading}
          openType='getPhoneNumber'
          onGetPhoneNumber={handleGetPhoneNumber}
          className='w-[420px] h-[94px] text-primary font-bold'
          disabled={!agree}
        >
          手机号快捷登录
        </Button>

        {renderAgreeNode()}
        {renderServiceNode()}
      </View>
    </View>
  );
}
